package com_.dxy_.test_.transaction_;

import com_.dxy_.test_.common_.dao_.UserDao;
import com_.dxy_.test_.common_.pojo_.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Description 事务测试ServiceImpl
 * @Author dangxianyue
 * @Date 2022/10/13 10:19
 */
@Service
public class TransactionTestServiceImpl implements TransactionTestService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TransactionTemplate transactionTemplate;


    @Override
    public String saveUserV1() throws Exception {

        //测试类内调用声明式事务方法，this.，调用的不是代理类，AOP不生效
//        return saveUserV2();

        //测试类内调用编程式事务方法
        return saveUserV3();
    }

    @Override
    @Transactional
    //没有指定rollbackFor，默认是RuntimeException、Error生效，不包括检查型异常Exception
    //声明式事务，只能细化到方法粒度，而且必须类外调用
    public String saveUserV2() throws Exception {
        User user = new User();
        user.setName("林七夜");
        userDao.insert(user);
        if (StringUtils.isNotBlank(user.getId())) {
            //异常必须抛出，才能感知生效
//        int i = 1/0;//模拟RuntimeException
//            throw new Exception("模拟检查型异常");
        }
        return user.getId();
    }

    @Override
    public String saveUserV3() throws Exception {
        return transactionTemplate.execute(status -> {
            User user = new User();
            user.setName("韩立");
            userDao.insert(user);
            if (StringUtils.isNotBlank(user.getId())) {
                System.out.println("模拟异常！");
                int i = 1/0;
            }
            return user.getId();
        });
    }

    @Override
    public String saveUserV4() throws Exception {
        return transactionTemplate.execute(status -> {
            try {
                User user = new User();
                user.setName("韩立");
                userDao.insert(user);
                if (StringUtils.isNotBlank(user.getId())) {
                    System.out.println("模拟异常！");
                    throw new Exception("模拟检查型异常");
                }
                return user.getId();
            } catch (Exception e) {
                e.printStackTrace();

                //(1)要么手动回滚
                //status.setRollbackOnly();
                //return null;

                //(2)要么包装成RuntimeException，让框架回滚
                throw new RuntimeException(e);
            }
        });
    }
}
